package com.foreknow.elm.controller;

import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.service.impl.CartServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class CartController {
    private CartService service = new CartServiceImpl();
    /**
     * 根据用户编号查询此用户所有购物车信息
     * 根据用户编号和商家编号，查询此用户购物车中某个商家的所有购物车信息
     * @param request
     * @return
     * @throws Exception
     */
    public Object listCart(HttpServletRequest request)throws Exception{
        String userId = request.getParameter("userId");
        List<Cart> list= new ArrayList<>();
        try{
            Integer businessId = Integer.valueOf(request.getParameter("businessId"));
            list = service.listCart(userId,businessId);
        }catch(Exception e){
            list = service.listCart(userId);
        }
        return list;
    }

    /**
     * 向购物车表中添加一条记录
     * @param request
     * @return
     * @throws Exception
     */
    public Integer saveCart(HttpServletRequest request)throws Exception{
        String userId = request.getParameter("userId");
        Integer businessId = Integer.valueOf(request.getParameter("businessId"));
        Integer foodId = Integer.valueOf(request.getParameter("foodId"));
        Integer quantity = Integer.valueOf(request.getParameter("quantity"));
        Integer result = service.saveCart(userId, businessId, foodId,quantity);
        return result;
    }

    /**
     * 根据用户编号、商家编号、食品编号更新数量
     * @param request
     * @return
     * @throws Exception
     */
    public Object updateCart(HttpServletRequest request)throws Exception{
        Cart cart = new Cart();
        cart.setQuantity(Integer.valueOf(request.getParameter("quantity")));
        cart.setUserId(request.getParameter("userId"));
        cart.setBusinessId(Integer.valueOf(request.getParameter("businessId")));
        cart.setFoodId(Integer.valueOf(request.getParameter("foodId")));
        Integer result = service.updateCart(cart);
        return result;
    }

    /**
     * 根据用户编号、商家编号、食品编号删除购物车表中的一条食品记录
     *    ​           根据用户编号、商家编号删除购物车表中的多条条记录
     * @param request
     * @return
     * @throws Exception
     */
    public Object removeCart(HttpServletRequest request)throws Exception{
        int result=0;
        String userId = request.getParameter("userId");
        Integer businessId= Integer.valueOf(request.getParameter("businessId"));
        try{
            Integer foodId= Integer.valueOf(request.getParameter("foodId"));
            result=service.removeCart(userId,businessId,foodId);
        }catch (Exception e){
            result = service.removeCart(userId, businessId);
        }

        return result;
    }
}
